//
//  JXUtils.swift
//  SwiftBaseProject
//
//  Created by 苏州巨细 on 2018/5/22.
//  Copyright © 2018年 苏州巨细. All rights reserved.
//

import Foundation
import TZImagePickerController

/// 管理工具类
class JXUtils {
    
    /// 按钮倒计时
    ///
    /// - Parameters:
    ///   - timeOut: 开始时间
    ///   - btn: 按钮
    class func countDown(_ timeOut: Int, btn: UIButton){
        
        //倒计时时间
        var timeout = timeOut
        let queue:DispatchQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default)
        let _timer:DispatchSource = DispatchSource.makeTimerSource(flags: [], queue: queue) as! DispatchSource
        _timer.schedule(wallDeadline: DispatchWallTime.now(), repeating: .seconds(1))
        
        //每秒执行
        _timer.setEventHandler(handler: { () -> Void in
            if(timeout<=0){ //倒计时结束，关闭
                
                _timer.cancel();
                DispatchQueue.main.sync(execute: { () -> Void in
                    btn.setTitle("重新获取", for: .normal)
                    btn.isEnabled = true
                    btn.layer.backgroundColor = UIColor.white.cgColor
                })
            }else{//正在倒计时
                
                let seconds = timeout
                DispatchQueue.main.sync(execute: { () -> Void in
                    btn.setTitle("\(seconds)s", for: .disabled)
                    btn.isEnabled = false
                    btn.layer.backgroundColor = UIColor.gray.cgColor
                })
                timeout -= 1;
            }
        })
        _timer.resume()
    }
    
    /// 展示本地相册
    ///
    /// - Parameters:
    ///   - maxNum: 最大照片选择数
    ///   - block: 照片数组
    class func showLocalAlbum(maxNum: Int, completionBlock block: @escaping (_ phtotoArr: [UIImage]?) -> Void) -> () {
        let imagePickerVC = TZImagePickerController.init(maxImagesCount: maxNum, delegate: nil)
        //不允许选择原图
        imagePickerVC?.allowPickingOriginalPhoto = false
        //不允许选择视频
        imagePickerVC?.allowPickingVideo = false
        imagePickerVC?.preferredLanguage = "zh-Hans"
        imagePickerVC?.didFinishPickingPhotosHandle = { photos, assets, isSelectOriginalPhoto in
            block(photos)
        }
        
        let currentVC = JXUtils.currentViewController()
        
        currentVC!.present(imagePickerVC!, animated: true, completion: nil)
    }
    
    /// 获取当前控制器
    ///
    /// - Returns: 当前控制器ViewController
    class func currentViewController() -> UIViewController? {
        
        guard let window = UIApplication.shared.windows.first else { return nil }
        var tempView: UIView?
        for subview in window.subviews.reversed() {
            
            if subview.classForCoder.description() == "UILayoutContainerView"
            {
                tempView = subview
                break
                
            }
        }
        if tempView == nil {
            tempView = window.subviews.last
            
        }
        var nextResponder = tempView?.next
        var next: Bool {
            return !(nextResponder is UIViewController) || nextResponder is UINavigationController || nextResponder is UITabBarController }
        while next{
            tempView = tempView?.subviews.first
            if tempView == nil { return nil }
            nextResponder = tempView!.next
            
        }
        return nextResponder as? UIViewController
    }
    
    /// 返回登陆界面
    class func backToLoginController() {
        let window: UIWindow? = UIApplication.shared.keyWindow
        if (window?.rootViewController is UINavigationController) {
            let nac = window?.rootViewController as? UINavigationController
            for vc: UIViewController? in nac?.viewControllers ?? [UIViewController?]() {
                if (vc is BaseViewController) {
                    vc?.navigationController?.popToRootViewController(animated: true)
                }
            }
        }
    }
    
    class func openTelephoneView(withPhoneNum num: String?) {
        //去除电话号码中的空格
        let noSpceNum = num?.replacingOccurrences(of: " ", with: "")
        let str = "tel:\(noSpceNum ?? "")"
        let application = UIApplication.shared
        let url = URL.init(string: str)
        
        if #available(iOS 10.0, *) {
            application.open(url!, options: [:], completionHandler: { success in
                //OpenSuccess=选择 呼叫 为 1  选择 取消 为0
                print("OpenSuccess=\(success)")
            })
        } else {
            application.openURL(url!)
        }
    }
    
    /// 获取app当前版本号
    ///
    /// - Returns: 当前版本号
    class func currentVersion() -> (String) {
        let dict = Bundle.main.infoDictionary
        let verStr = dict!["CFBundleShortVersionString"] as? String
        return verStr ?? ""
    }
    
    /// 传入日期转换成聊天显示时间
    ///
    /// - Parameter date: 日期
    /// - Returns: 时间字符串
    class func changeToShowChatTime(date: Date) -> (String) {
        
        if date.isToday {
            return date.toFormat("hh:mm")
        }
        else if date.compare(.isThisWeek) {
            return "\(date.weekdayName(.`default`))"+date.toFormat(" hh:mm")
        }
        else if date.compare(.isThisYear) {
            return date.toFormat("MM-dd hh:mm")
        }
        else {
            return date.toFormat("yyyy-MM-dd hh:mm")
        }
    }
    
    /// 计算文本高度
    /// - Parameters:
    ///   - text: 文本
    ///   - font: 字体大小
    /// - Returns:
    class func calcRealTextSize(text:String, font:UIFont) -> CGSize {
        let singleLineMaxWidth = UIScreen.main.bounds.width * 0.6
        
        let tmpTextView = UITextView(frame: .zero)
        tmpTextView.font = font
        tmpTextView.text = text
        let realTextSize = tmpTextView.sizeThatFits(CGSize(width: singleLineMaxWidth, height: .greatestFiniteMagnitude))
        return realTextSize
    }
    
    /// 计算文本宽度
    /// - Parameters:
    ///   - text: 文本
    ///   - font: 字体大小
    ///   - height: 行高
    /// - Returns:
    class func calcContentWidth(text:String, font:UIFont, height:CGFloat) -> CGFloat {
        let singleLineMaxHeight = height
        
        let tmpTextView = UITextView(frame: .zero)
        tmpTextView.font = font
        tmpTextView.text = text
        let realTextSize = tmpTextView.sizeThatFits(CGSize(width: .greatestFiniteMagnitude, height: singleLineMaxHeight))
        return realTextSize.width
    }
    
}

extension UIScreen {
    func size() -> (CGSize) {
        return UIScreen.main.bounds.size
    }
    
}

/// iPhone屏幕尺寸
///
/// - ThreeHalfInch: 3.5英寸,4,4s
/// - FourInch: 4英寸,5,5s,C,Se
/// - FourSevenInch: 4.7英寸,6,7,8,S
/// - FiveHalfInch: 5.5英寸,P
/// - FiveEightInch: 5.8英寸，X
enum ScreenInch {
    case ThreeHalfInch
    case FourInch
    case FourSevenInch
    case FiveHalfInch
    case FiveEightInch
}

/// 计算iPhone尺寸
///
/// - Returns: 屏幕英寸
func calculateScreenInch() -> (ScreenInch) {
    switch kScreenH {
    case 480.0:
        return .ThreeHalfInch
    case 568.0:
        return .FourInch
    case 667.0:
        return .FourSevenInch
    case 736.0:
        return .FiveHalfInch
    case 812.0:
        return .FiveEightInch
        
    default:
        return .ThreeHalfInch
    }
}

/// 根据6s的尺寸来适配宽度
///
/// - Parameter w: 需要适配的宽度
/// - Returns: 当前屏幕对应宽度
func adapterWidth6S(w: CGFloat) -> CGFloat {
    return w*(kScreenW/375)
}


extension JXUtils {
    
    class func takePhoto(viewController: UIViewController&UIImagePickerControllerDelegate&UINavigationControllerDelegate) -> () {
        
        let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
        if (authStatus == .restricted || authStatus == .denied) && iOS_Version_Later(VersionNum: 7) {
            
            let title = "提示"
            let message = "对不起，您没有打开相机权限，请先去设置内打开"
            if iOS_Version_Later(VersionNum: 8) {
                UIAlertController.showMsgWithAlertView(showType: .OnlyConfirmButton, title: title, message: message, andController: JXUtils.currentViewController()!, actionTitleArr: nil)
            }
        }
        else if authStatus == .notDetermined {
            if iOS_Version_Later(VersionNum: 7) {
                AVCaptureDevice.requestAccess(for: .video) { (granted) in
                    if granted {
                        DispatchQueue.main.async {
                            let imagePickerVC = UIImagePickerController.init()
                            imagePickerVC.delegate = viewController
                            imagePickerVC.allowsEditing = true
                            imagePickerVC.sourceType = .camera
                            JXUtils.currentViewController()?.present(imagePickerVC, animated: true, completion: nil)
                        }
                    }
                }
            }
        }
        else{
            let imagePickerVC = UIImagePickerController.init()
            imagePickerVC.delegate = viewController
            imagePickerVC.allowsEditing = true
            imagePickerVC.sourceType = .camera
            JXUtils.currentViewController()?.present(imagePickerVC, animated: true, completion: nil)
        }
    }
}

enum RecordState {
    case requestRecord
    case canRecord
    case canNotRecord
}


// MARK: - 判断设备权限
extension JXUtils {
    
    /// 判断当前设备语音权限
    ///
    /// - Parameter completion: 语音权限状态
    class func phoneRecordState(completion: @escaping (RecordState) -> Void) -> () {
        
        let videoAuthStatus = AVCaptureDevice.authorizationStatus(for: .audio)
        
        switch videoAuthStatus {
        case .notDetermined:
            AVAudioSession().requestRecordPermission { (granted) in
                completion(.requestRecord)
            }
        case .denied,.restricted:
            completion(.canNotRecord)
            
        default:
            completion(.canRecord)
        }
    }
    
}

extension JXUtils {
    
    /// 清楚webview缓存
    class func cleanCacheAndCookie() -> () {
        
        let storage = HTTPCookieStorage.shared
        if let cookies = storage.cookies {
            
            for cookie in cookies {
                storage.deleteCookie(cookie)
            }
        }
        
        URLCache.shared.removeAllCachedResponses()
        URLCache.shared.diskCapacity = 0
        URLCache.shared.memoryCapacity = 0
        
        //删除wkwebview的localstorage
        if iOS_Version_Later(VersionNum: 9) {
            
            let websiteDataTypes = WKWebsiteDataStore.allWebsiteDataTypes()
            let dateFrom = Date.init(timeIntervalSince1970: 0)
            
            WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes, modifiedSince: dateFrom) {
                
                
            }
        }
    }
    
}

